package org.example.hypersonaltools.scene;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.gitee.milklynk.DeepSeek;
import io.gitee.milklynk.vo.enums.Model;
import io.gitee.milklynk.vo.enums.Role;
import io.gitee.milklynk.vo.request.ChatRequest;
import io.gitee.milklynk.vo.request.Message;
import io.gitee.milklynk.vo.response.ChatResponse;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import org.example.hypersonaltools.tool.DeepSeekDataOptionTools;

import java.util.ArrayList;
import java.util.List;

public class DeepSeekChatScene implements FXScene {
    private final Scene scene;
    private final VBox root;
    private TextArea chatArea;
    private TextField inputField;
    private Button sendButton;
    private List<Message> messages = new ArrayList<>();
    private DeepSeek deepSeek = new DeepSeek("sk-faade992b762479b8ae72cb9af20719a");
    private boolean isRequesting = false;
    private Boolean isAgreed = false;

    public DeepSeekChatScene() {
        root = new VBox();
        scene = new Scene(root, 800, 600);

        initializeUI();
        setupEventListeners();
    }

    private void initializeUI() {
        // 创建聊天内容显示区域
        chatArea = new TextArea();
        chatArea.setEditable(false);
        chatArea.setWrapText(true);
        VBox.setVgrow(chatArea, Priority.ALWAYS);

        // 创建输入消息的文本框
        inputField = new TextField();
        inputField.setPromptText("输入消息...Enter+右Shift发送");
        HBox.setHgrow(inputField, Priority.ALWAYS);

        // 创建发送按钮
        sendButton = new Button("发送");

        // 创建水平布局用于输入框和按钮
        HBox inputBox = new HBox(inputField, sendButton);
        inputBox.setSpacing(10);

        // 将组件添加到根布局
        root.getChildren().addAll(chatArea, inputBox);
    }

    private void setupEventListeners() {
        // 回车键 + 右Shift发送
        inputField.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            if (event.getCode() == KeyCode.ENTER && event.isShiftDown() && !isRequesting) {
                handleSendMessage();
            }
        });

        // 按钮点击发送
        sendButton.setOnAction(event -> {
            if (!isRequesting) {
                handleSendMessage();
            }
        });
    }

    private void handleSendMessage() {
        String userInput = inputField.getText().trim();
        if (userInput.equals("同意")) {
            isAgreed = true;
        }
        if (!userInput.isEmpty()) {
            try {
                // 立即显示用户消息
                Message userMessage = Message.builder()
                        .role(Role.USER.getType())
                        .content(userInput)
                        .build();
                messages.add(userMessage);

                Platform.runLater(() -> {

                    chatArea.appendText("用户: " + userInput + "\n");
                    inputField.clear();
                    setUIState(true); // 禁用输入
                });

                // 创建异步任务
                Task<ChatResponse> chatTask = new Task<>() {
                    @Override
                    protected ChatResponse call() throws Exception {
                        ChatRequest request = ChatRequest.builder()
                                .model(Model.DeepSeek_V3.getName())
                                .messages(messages)
                                .build();
                        return deepSeek.chatCompletion(request);
                    }
                };

                chatTask.setOnSucceeded(event -> {
                    ChatResponse response = chatTask.getValue();
                    if (response != null && response.getChoices() != null) {
                        String assistantReply = response.getChoices().get(0).getMessage().getContent();
                        Message assistantMessage = Message.builder()
                                .role(Role.ASSISTANT.getType())
                                .content(assistantReply)
                                .build();
                        messages.add(assistantMessage);

                        Platform.runLater(() -> {
                            if (isAgreed){
                                JSONObject jsonObject = JSON.parseObject(assistantReply);
                                DeepSeekDataOptionTools data = jsonObject.toJavaObject(DeepSeekDataOptionTools.class);
                                data.run();
                                System.out.println(data);
                            }
                            chatArea.appendText("助手: " + assistantReply + "\n\n");
                            setUIState(false); // 恢复输入
                        });
                    }
                });

                chatTask.setOnFailed(event -> {
                    Platform.runLater(() -> {
                        chatArea.appendText("错误: " + chatTask.getException().getMessage() + "\n");
                        setUIState(false);
                    });
                });

                new Thread(chatTask).start();

            } catch (Exception e) {
                Platform.runLater(() -> {
                    chatArea.appendText("错误: " + e.getMessage() + "\n");
                    setUIState(false);
                });
            }
        }
    }

    private void setUIState(boolean isProcessing) {
        isRequesting = isProcessing;
        inputField.setDisable(isProcessing);
        sendButton.setDisable(isProcessing);
    }

    @Override
    public Scene getScene() {
        return scene;
    }

    @Override
    public void onEnter() {
        // 初始化时可以添加系统消息
//        Message systemMessage = Message.builder()
//                .role(Role.SYSTEM.getType())
//                .content("无论用户说什么你都得回答“阿巴阿巴”")
//                .build();
//        messages.add(systemMessage);
    }

    @Override
    public void onExit() {
        // 清理资源
        messages.clear();
    }
}
